import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity,
  ListView,
  ScrollView
} from 'react-native';

var Util = require("./../common/util");
var SearchBar = require("./../common/searchBar");
var  ServiceURL = require("./../common/service");
var BookItem = require("./book_item");

var BookList = React.createClass({
  getInitialState: function () {
    var ds = new ListView.DataSource({
      rowHasChanged:(r0, r1) => r0 !== r1
    });
    return {
      dataSource:ds,
      show:false,
      keywords:"React"
    };
  },
  getData:function () {
    this.setState({
      show:false
    })
    //请求数据
    var that = this;
    var url = ServiceURL.book_search + "?count=20&q=" + this.state.keywords
    Util.getRequest(url,function (data) {
      // 成功
      if (!data.books || data.books.length == 0) {
        return alert("未找到相关书籍")
      }
      var ds = new ListView.DataSource({
        rowHasChanged:(r0, r1) => r0 !== r1
      })
      that.setState({
        show:true,
        dataSource:ds.cloneWithRows(data.books)
      })
    },function (err) {
      alert("请求失败")
    })
  },
  _changeText:function(text) {
    this.setState({
      keywords:text
    })
  },
  _searchPress:function() {
    this.getData()
  },
  render: function () {
    return (
        <ScrollView>
          <SearchBar
              placeholder="请输入图书名"
              onPress={this._searchPress}
              onChangeText={this._changeText}
          />
          {
            this.state.show
                ?
                <ListView
                    dataSource={this.state.dataSource}
                    initialListSize={10}
                    renderRow={this._renderRow}
                    renderSeparator={this._renderSeparator}
                />
                :
                Util.loading
          }
        </ScrollView>
    )
  },
  componentDidMount:function () {
    this.getData()
  },
  _renderRow: function (book) {
    return <BookItem book={book}/>
  },
  _renderSeparator:function (sectionID, rowID) {
    var style = {
      height:1,
      backgroundColor:"#ccc"
    }
    return <View style={style} key={sectionID+rowID}/>
  }
});

module.exports = BookList;